package com.linc.facerecognitionsi.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.linc.facerecognitionsi.R;
import com.linc.facerecognitionsi.database.FaceTemplateSQLiteHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

public class AppStartActivity extends Activity{
	private final String TAG="AppStartActivity";
    private CopyFileHandler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_appstart);
        mHandler = new CopyFileHandler(this);
		startCopyDBThread();
	}
	

	private void startCopyDBThread(){
		Log.d(TAG, "startCopyDBThread");
		new Thread(new Runnable() {
			@Override
			public void run() {
				copyDBFile();
				Message msg=mHandler.obtainMessage();
                mHandler.sendMessage(msg);
			}
		}).start();
	}

	private void copyDBFile() {
		Log.d(TAG, "DetectDB-in");
		try {
            String databasePath = getFilesDir().getPath();
            Log.d(TAG,"db path: "+databasePath);
			String databaseFilename = databasePath+"/"+FaceTemplateSQLiteHelper.DB_NAME;
			File dir = new File(databasePath);
			if (!dir.exists()) {
                dir.mkdir();
                Log.d(TAG,"mkdir success");
            }

			if (!(new File(databaseFilename)).exists()) {
				InputStream is = getResources().openRawResource(R.raw.face);
				FileOutputStream fos = new FileOutputStream(databaseFilename);
				byte[] buffer = new byte[1024];
				int count;
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}

				fos.close();
				is.close();
				Log.d(TAG,"DetectDB-move db success");
			}
		} catch(Exception e) {
			e.printStackTrace();
			Log.e(TAG, "DetectDB-failed: "+e.getMessage());
		}
	}

    private static class CopyFileHandler extends Handler {
        WeakReference<AppStartActivity> mActivity;
        public CopyFileHandler(AppStartActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        public void handleMessage(Message msg) {
            final AppStartActivity activity = mActivity.get();
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    Intent it = new Intent(activity, MainActivity.class);
                    activity.startActivity(it);
                    activity.finish();
                }
            };
            timer.schedule(task, 1500);
        }
    }
}
